﻿using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace com.wei8808.utility
{
    /// <summary>
    /// 密码加密
    /// </summary>
    public class EncryptPassWord
    {
        // 密钥8位
        private static string GenerateKey()
        {
            return "WEIX8808";
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="aPassWord"></param>
        /// <returns></returns>
        public static string EncryptString(string aPassWord)
        {
            if (string.IsNullOrEmpty(aPassWord)) return null;
            var key = GenerateKey();
            var data = Encoding.UTF8.GetBytes(aPassWord);
            var des = new DESCryptoServiceProvider
            {
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(key)
            };
            var desencrypt = des.CreateEncryptor();
            var result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(result);
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="aPassWord"></param>
        /// <returns></returns>
        public static string DecryptString(string aPassWord)
        {
            if (string.IsNullOrEmpty(aPassWord)) return null;
            var key = GenerateKey();
            var sInput = aPassWord.Split("-".ToCharArray());
            var data = new byte[sInput.Length];
            for (int i = 0; i < sInput.Length; i++)
            {
                data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
            }
            var des = new DESCryptoServiceProvider
            {
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(key)
            };
            var desencrypt = des.CreateDecryptor();
            var result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Encoding.UTF8.GetString(result);
        }
    }
}
